//
//  HLTabBarViewController.m
//  YueYue
//
//  Created by hulu001 on 2023/5/17.
//

#import "HLTabBarViewController.h"

#import "HLNavigationController.h"
#import "HLHomeViewController.h"
#import "HLSquareViewController.h"
#import "HLSquareVideoViewController.h"
#import "HLMineViewController.h"
#import "HLMessageViewController.h"
#import "HLHomeLoveBellView.h"
#import "HLUpdateTipView.h"
#import "YMTranslacteRequest.h"
#import <NIMSDK/NIMSDK.h>
#import "HLMessagelimitRequest.h"

@interface HLTabBarViewController ()<NIMConversationManagerDelegate, NIMSDKConfigDelegate>

@property (nonatomic, strong) NSTimer *timer;
@end

@implementation HLTabBarViewController

- (void)viewDidLoad {
    [super viewDidLoad];
//    [self requestMsgList];
    [NIMSDKConfig sharedConfig].delegate = self;
    [self customizeInterface];
    if (![HLRunTime shareInstance].isFood) {
        [HLHelper authorizationStatus];
    }
    [HLHelper userInfo];
    // 检查更新
    [HLUpdateTipView requestUpdateWithBlock:^{
        //[QMUITips showWithText:@"没有可用版本更新"];
    } isCoerce:YES];
    
    [NIMSDK.sharedSDK.conversationManager addDelegate:self];
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        [NIMSDK.sharedSDK.conversationManager addDelegate:self];
        NSInteger count = [NIMSDK.sharedSDK.conversationManager allUnreadCount];
        [self updateUnreadCount:count];
    });
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(notification:) name:HLVideoViewDidChangeNotification object:nil];
    if (![HLRunTime shareInstance].isFood) {
        [self setupTimer];
    }
    
    // 保存自己的语种
    [[YMTranslacteRequest.alloc initWithType:YMTranslacteRequestTypeSaveSelfLang] startWithCompletionBlockWithSuccess:^(__kindof YTKBaseRequest * _Nonnull request) {
    } failure:^(__kindof YTKBaseRequest * _Nonnull request) {
    }];
    [[YMTranslacteRequest.alloc initWithType:YMTranslacteRequestTypeGetTimeout] startWithCompletionBlockWithSuccess:^(__kindof YMTranslacteRequest * _Nonnull request) {
        if (request.isSuccess) {
            id obj = request.result[@"data"];
            if ([obj isKindOfClass:NSNumber.class]) {
                NSNumber *number = obj;
                HLHelper.shareInstance.cache[@"GPTranslactionTimeoutKey"] = number;
            }
        }
    } failure:^(__kindof YTKBaseRequest * _Nonnull request) {
        
    }];
}

- (void)invalidateTimer
{
    [_timer invalidate];
    _timer = nil;
}

- (void)setupTimer
{
    [self invalidateTimer]; // 创建定时器前先停止定时器，不然会出现僵尸定时器，导致轮播频率错误
    
    NSTimer *timer  = [NSTimer scheduledTimerWithTimeInterval:1.0 target:self selector:@selector(timerAction) userInfo:nil repeats:YES];
    
    [[NSRunLoop mainRunLoop] addTimer:timer forMode:NSRunLoopCommonModes];
    _timer = timer;
}


- (void)timerAction
{
    if ([HLLoginModel dataWithKeychain]){
        [HLHomeLoveBellView bell];
    }
}

/**
*  tabBarItem 的选中和不选中文字属性、背景图片
*/
- (void)customizeInterface {
   
   // 设置背景图片
   UITabBar *tabBarAppearance = [UITabBar appearance];
   [tabBarAppearance setBackgroundColor:UIColorWhite];
   [tabBarAppearance setShadowImage:[[UIImage alloc] init]];
    
    [self.tabBar.standardAppearance qmui_applyItemAppearanceWithBlock:^(UITabBarItemAppearance * _Nonnull itemAppearance) {
        itemAppearance.selected.titleTextAttributes = @{NSForegroundColorAttributeName:HLTextColor1};
        itemAppearance.normal.titleTextAttributes = @{NSForegroundColorAttributeName:HLTextColor2};
    }];
    
    self.delegate = self;
    [self hideTabBarShadowImageView];
    NSArray *arr = [self tabBarItemsAttributesForController];
    self.tabBarController.selectedIndex = 0;
    self.tabBarItemsAttributes = arr;
    
    [self setViewControllers:[self viewControllersForTabBar]];
}


- (NSArray *)tabBarItemsAttributesForController
{
    
    
    NSDictionary *homeTabBarItemsAttributes = @{
                                                 CYLTabBarItemTitle : @"交友",
                                                 CYLTabBarItemImage : @"tab_home",
                                                 CYLTabBarItemSelectedImage : @"tab_homes",
                                                 };
    
    NSDictionary *squareTabBarItemsAttributes = @{
                                                 CYLTabBarItemTitle : @"闪聊",
                                                 CYLTabBarItemImage : @"tab_square",
                                                 CYLTabBarItemSelectedImage : @"tab_squares",
                                                 };
    
    NSDictionary *msgTabBarItemsAttributes = @{
                                                 CYLTabBarItemTitle : @"消息",
                                                 CYLTabBarItemImage : @"tab_msg",
                                                 CYLTabBarItemSelectedImage : @"tab_msgs",
                                                 };
    
   NSDictionary *mineTabBarItemsAttributes = @{
                                                CYLTabBarItemTitle : @"我的",
                                                CYLTabBarItemImage : @"tab_mine",
                                                CYLTabBarItemSelectedImage : @"tab_mines",
                                                };
    
    
    


   NSArray *tabBarItemsAttributes = @[homeTabBarItemsAttributes,
                                      squareTabBarItemsAttributes,
                                      msgTabBarItemsAttributes,
                                      mineTabBarItemsAttributes,
                                      ];

   return tabBarItemsAttributes;
}

- (NSArray *)tabBarVideoItemsAttributesForController
{
    
    
    NSDictionary *homeTabBarItemsAttributes = @{
                                                 CYLTabBarItemTitle : @"交友",
                                                 CYLTabBarItemImage : @"tab_home",
                                                 CYLTabBarItemSelectedImage : @"tab_v_homes",
                                                 };
    
    NSDictionary *squareTabBarItemsAttributes = @{
                                                 CYLTabBarItemTitle : @"闪聊",
                                                 CYLTabBarItemImage : @"tab_v_square",
                                                 CYLTabBarItemSelectedImage : @"tab_squares",
                                                 };
    
    NSDictionary *msgTabBarItemsAttributes = @{
                                                 CYLTabBarItemTitle : @"消息",
                                                 CYLTabBarItemImage : @"tab_v_msg",
                                                 CYLTabBarItemSelectedImage : @"tab_msgs",
                                                 };
    
   NSDictionary *mineTabBarItemsAttributes = @{
                                                CYLTabBarItemTitle : @"我的",
                                                CYLTabBarItemImage : @"tab_v_mine",
                                                CYLTabBarItemSelectedImage : @"tab_mines",
                                                };
    
    
    


   NSArray *tabBarItemsAttributes = @[homeTabBarItemsAttributes,
                                      squareTabBarItemsAttributes,
                                      msgTabBarItemsAttributes,
                                      mineTabBarItemsAttributes,
                                      ];

   return tabBarItemsAttributes;
}


- (NSArray *)viewControllersForTabBar {
    
    UIViewController *homeVC;
    UIViewController *squareVC;
    if ([HLRunTime shareInstance].isFood) {
        squareVC = [[HLSquareVideoViewController alloc] init];
        homeVC = [[HLHomeViewController alloc] init];
    } else {
        squareVC = [[HLSquareViewController alloc] init];
        homeVC = [[HLHomeViewController alloc] init];
    }
    
    homeVC.hidesBottomBarWhenPushed = NO;
    HLNavigationController *navHomeVC = [[HLNavigationController alloc] initWithRootViewController:homeVC];
    [navHomeVC cyl_setHideNavigationBarSeparator:YES];
    
    squareVC.hidesBottomBarWhenPushed = NO;
    HLNavigationController *navSquareVC = [[HLNavigationController alloc] initWithRootViewController:squareVC];
    [navSquareVC cyl_setHideNavigationBarSeparator:YES];
    
    HLMineViewController *mineVC = [[HLMineViewController alloc] init];
    mineVC.hidesBottomBarWhenPushed = NO;
    HLNavigationController *navMineVC = [[HLNavigationController alloc] initWithRootViewController:mineVC];
    [navMineVC cyl_setHideNavigationBarSeparator:YES];

    
    HLMessageViewController *messageVC = [[HLMessageViewController alloc] init];
    messageVC.hidesBottomBarWhenPushed = NO;
    HLNavigationController *navMessageVC = [[HLNavigationController alloc] initWithRootViewController:messageVC];
    [navMessageVC cyl_setHideNavigationBarSeparator:YES];
    
    return @[navHomeVC, navSquareVC, navMessageVC, navMineVC];
}

- (void)notification:(NSNotification *)noti
{
    UITabBarAppearance *tabBarAppearance = [[UITabBarAppearance alloc] init];
    
    if ([noti.object boolValue]){
        
        tabBarAppearance.stackedLayoutAppearance.normal.titleTextAttributes = @{NSForegroundColorAttributeName:HLTextColor3};
        tabBarAppearance.stackedLayoutAppearance.selected.titleTextAttributes = @{NSForegroundColorAttributeName:UIColorWhite};
        self.tabBar.backgroundColor = UIColorBlack;
        
    } else {
        self.tabBar.backgroundColor = UIColorWhite;
        tabBarAppearance.stackedLayoutAppearance.normal.titleTextAttributes = @{NSForegroundColorAttributeName:HLTextColor2};
        tabBarAppearance.stackedLayoutAppearance.selected.titleTextAttributes = @{NSForegroundColorAttributeName:HLTextColor1};
    }
    
    for (int i = 0; i < self.viewControllers.count; i++) {
        
        UIViewController *vc = self.viewControllers[i];
        
        if ([noti.object boolValue]){
            NSArray *items = [self tabBarVideoItemsAttributesForController];
            NSDictionary *dic = items[i];
            vc.tabBarItem.image = [UIImageMake(dic[CYLTabBarItemImage]) imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal];
            vc.tabBarItem.selectedImage = [UIImageMake(dic[CYLTabBarItemSelectedImage]) imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal];
            
        
        } else {
            NSArray *items = [self tabBarItemsAttributesForController];
            NSDictionary *dic = items[i];
            vc.tabBarItem.image = [UIImageMake(dic[CYLTabBarItemImage]) imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal];
            vc.tabBarItem.selectedImage = [UIImageMake(dic[CYLTabBarItemSelectedImage]) imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal];
        }
        vc.tabBarItem.standardAppearance = tabBarAppearance;
    }
    
}


- (BOOL)tabBarController:(UITabBarController *)tabBarController shouldSelectViewController:(UIViewController *)viewController API_AVAILABLE(ios(3.0));
{
    BOOL should = YES;
    [self updateSelectionStatusIfNeededForTabBarController:tabBarController shouldSelectViewController:viewController shouldSelect:should];
    return should;
}

#pragma mark - NIM
- (void)didAddRecentSession:(NIMRecentSession *)recentSession totalUnreadCount:(NSInteger)totalUnreadCount
{
    [self updateUnreadCount:totalUnreadCount];
}

- (void)didUpdateRecentSession:(NIMRecentSession *)recentSession totalUnreadCount:(NSInteger)totalUnreadCount
{
    [self updateUnreadCount:totalUnreadCount];
}

- (void)didLoadAllRecentSessionCompletion
{
    [self updateUnreadCount:[NIMSDK.sharedSDK.conversationManager allUnreadCount]];
}

- (void)didRemoveRecentSession:(NIMRecentSession *)recentSession totalUnreadCount:(NSInteger)totalUnreadCount
{
    [self updateUnreadCount:totalUnreadCount];
}

- (void)allMessagesRead
{
    [self updateUnreadCount:0];
}

- (void)updateUnreadCount:(NSInteger)unreadCount
{
    NSInteger index = 2;
    
    self.viewControllers[index].cyl_badgeBackgroundColor = [UIColor qmui_colorWithHexString:@"#FC4B69"];
    self.viewControllers[index].cyl_badgeMaximumBadgeNumber = 200;
    self.viewControllers[index].cyl_badgeMargin = 4;
    [self.viewControllers[index] cyl_showBadgeValue:[NSString stringWithFormat:@"%zd",unreadCount] animationType:CYLBadgeAnimationTypeBounce];
    
    UIApplication.sharedApplication.applicationIconBadgeNumber = unreadCount;
}

- (void)dealloc
{
    [self invalidateTimer];
}

- (BOOL)shouldIgnoreMessage:(NIMMessage *)message
{
//    HLMessagelimitResponse *config = HLHelper.shareInstance.cache[@"limit_config"];
//    if (config) {
//        BOOL isIgnore = [config isNeedLimitWithHandler:^(BOOL needDeleteLimit) {
//        }];
//        return isIgnore;
//    }
    if (message.messageType == 100) {
        NIMCustomObject *object = (NIMCustomObject *)message.messageObject;
        
        if ([object.attachment isKindOfClass:NSClassFromString(@"HLGiftAttachment")]
            || [object.attachment isKindOfClass:NSClassFromString(@"HLVideoGuideAttachment")]
            || [object.attachment isKindOfClass:NSClassFromString(@"HLVideoGuideAttachment")]
            || [object.attachment isKindOfClass:NSClassFromString(@"HLRechargeAttachment")]
            || [object.attachment isKindOfClass:NSClassFromString(@"HLPayRemindAttachment")]
            || [object.attachment isKindOfClass:NSClassFromString(@"HLOtherRemidAttach")]
            || [object.attachment isKindOfClass:NSClassFromString(@"HLAccostAttachment")]) {
            return NO;
        }
        return YES;
    }
    
    return NO;
}

/// 请求消息限制的配置
- (void)requestMsgList
{
    [[HLMessagelimitRequest.alloc init] startWithCompletionBlockWithSuccess:^(__kindof HLMessagelimitRequest * _Nonnull request) {
        HLMessagelimitResponse *config = request.limitResponse;
        if (config) {
//            HLHelper.shareInstance.cache[@"limit_config"] = [HLMessagelimitResponse.alloc init];
            HLHelper.shareInstance.cache[@"limit_config"] = config;
        }
    } failure:^(__kindof HLMessagelimitRequest * _Nonnull request) {
        
    }];
}

@end
